/*
 * File Name：DrawableButton.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： DrawableButton.java
 * Modify By：res-jxliu
 * Modify Date：2015年2月12日
 * Modify Type：Add
 */
package com.ciwong.mobilelib.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.Button;

/**
 * 左边图片与文本一起居中的button
 * 
 * @author res-jxliu
 * @version ciwong v.1.0 2015年2月12日
 * @since ciwong v.1.0
 */
public class DrawableButton extends Button
{
    public DrawableButton(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    public DrawableButton(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public DrawableButton(Context context)
    {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        Drawable[] drawables = getCompoundDrawables();
        if (drawables != null)
        {
            Drawable drawableLeft = drawables[0];
            if (drawableLeft != null)
            {
                float textWidth = getPaint().measureText(getText().toString());
                int drawablePadding = getCompoundDrawablePadding();
                int drawableWidth = 0;
                drawableWidth = drawableLeft.getIntrinsicWidth();
                float bodyWidth = textWidth + drawableWidth + drawablePadding;
                setPadding(0, 0, (int) (getWidth() - bodyWidth), 0);
                canvas.translate((getWidth() - bodyWidth) / 2, 0);
            }
        }
        super.onDraw(canvas);
    }
}
